package HTTPServer;

import java.net.*;
import java.util.*;
import java.io.*;

public class GetMethod implements MethodStrategy {

    HTTPServerStrategy server;
    
    public GetMethod(HTTPServerStrategy server) {
        this.server=server;
    }
    
    public void processRequest(String request) throws IOException {
        String req = request.substring(4, request.length() - 9).trim();
        if (req.indexOf("/.") != -1 || req.endsWith("~")) {
            server.errorReport(server.getPOut(), server.getConnection(), "403", "Forbidden",
                    "You don't have permission to access " +
                    "the requested URL.");
        } else {
            String path = server.getWwwhome() + "/" + req;
            File f = new File(path);
            if (f.isDirectory() && !path.endsWith("/")) {
                server.getPOut().print("HTTP/1.0 301 Moved Permanently\r\n" +
                        "Location: http://" +
                        server.getConnection().getLocalAddress().getHostAddress() + ":" +
                        server.getConnection().getLocalPort() + req + "/\r\n\r\n");
                server.log(server.getConnection(), "301 Moved Permanently");
            } else {
                if (f.isDirectory()) {
                    path = path + "index.html";
                    f = new File(path);
                }
                try {
                    InputStream file = new FileInputStream(f);
                    String contenttype =
                            URLConnection.guessContentTypeFromName(path);
                    server.getPOut().print("HTTP/1.0 200 OK\r\n");
                    if (contenttype != null) {
                        server.getPOut().print("Content-Type: " + contenttype + "\r\n");
                    }
                    server.getPOut().print("Date: " + new Date() + "\r\n" +
                            "Server: DENIAL WebServer 1.0\r\n\r\n");
                    server.sendFile(file, server.getOut()); // send raw file 
                    server.log(server.getConnection(), "200 OK");
                } catch (FileNotFoundException e) {
                    server.errorReport(server.getPOut(), server.getConnection(), "404", "Not Found",
                            "The requested URL was not found " +
                            "on this server.");
                }
            }
        }
    }
}
